const BehaviorAll = require("../../../behaviors/behavior_all.js");
const ServiceUser = require("../../../service/service_user.js");
const ServiceSpread = require("../../../service/service_spread.js");
const App = getApp();

Component({
  /**
   * behaviors
   */
  behaviors: [BehaviorAll],
  /**
   * 页面的初始数据
   */
  data: {
    user: null,
    userInfo: null,
    shareImgUrl: null
  },

  methods: {
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
      const _this = this;
      _this.setData({
        user: App.globalData.user
      })
      //
      ServiceUser.getInfo(function (data) {
        _this.setData({ userInfo: data });
      });
      ServiceSpread.getShare(res => {
        _this.setData({ shareImgUrl: res.imgUrl });
      })
    },
    /**
     * 长按保存图片
     */
    saveImage: function(e){
      let url = e.currentTarget.dataset.url;
      const _this = this;
      //用户需要授权
      wx.getSetting({
        success: (res) => {
          if (!res.authSetting['scope.writePhotosAlbum']) {
            wx.authorize({
              scope: 'scope.writePhotosAlbum',
              success: () => {
                // 同意授权
                _this.saveImg1(url);
              },
              fail: (res) => {
                console.log(res);
              }
            })
          } else {
            // 已经授权了
            _this.saveImg1(url);
          }
        },
        fail: (res) => {
          console.log(res);
        }
      })
    },
    saveImg1(url) {
      wx.getImageInfo({
        src: url,
        success: (res) => {
          let path = res.path;
          wx.saveImageToPhotosAlbum({
            filePath: path,
            success: (res) => {
              console.log(res);
            },
            fail: (res) => {
              console.log(res);
            }
          })
        },
        fail: (res) => {
          console.log(res);
        }
      })
    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function (res) {
      const _this = this;
      // if (res.from === 'button') {
      // }
      const user = App.globalData.user;
      return {
        title: "我是：" + user.nickName,
        imageUrl: _this.data.b_service + _this.data.shareImgUrl,
        path: '/pages/index/index?id=' + user.id
      }
    }
  }

})